package cn.ybz21.hibot.resource;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import cn.ybz21.hibot.bean.App;
import cn.ybz21.hibot.bean.AppMonitor;
import cn.ybz21.hibot.bean.AppState;
import cn.ybz21.hibot.bean.Node;
import cn.ybz21.hibot.bean.ResultCode;
import cn.ybz21.hibot.service.AppMonitorService;
import cn.ybz21.hibot.util.FileUtil;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

@Path("/appMonitor")
public class AppMonitorResource {

	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public AppMonitor getDefaultTask() {
		List<App> apps=new AppMonitorService().getMonitorAppsByClientId("1");
		AppMonitor m=new AppMonitor();
		m.apps=apps;
		return m;
//		return "appMonitor  center";
	}

	@POST
	@Path("/uploadAppInfo")
	@Produces(MediaType.APPLICATION_JSON)
	public ResultCode publishTask(@FormParam("data") String data) {
		System.out.println("data:" + data);
		
		Gson gson = new Gson();
		AppMonitor AppMonitor = gson.fromJson(data,
				new TypeToken<AppMonitor>() {
				}.getType());
		new AppMonitorService().AddAppMonitor(AppMonitor);
		ResultCode rCode = new ResultCode(0);
		return rCode;
	}

	@GET
	@Path("/getAppDetail/clientId/{clientId}/name/{name}")
	@Produces(MediaType.APPLICATION_JSON)
	public List<Node> getClientById(@PathParam("clientId") String clientId,
			@PathParam("name") String name) {
		App app = new App();
		List<Node> nodes = new ArrayList<Node>();
		List<String> strs = FileUtil.readFileByLines("/home/ybz/桌面/sql");
		for (String str : strs) {
			Node node = new Node();
			String stt[] = str.split(" ");
			node.name = stt[0];
			node.pid = stt[1];
			node.cpu=Double.parseDouble(stt[2]);
			node.memory=Double.parseDouble(stt[3]);
			nodes.add(node);
		}

		return nodes;
		// return new AppMonitorService().getAppDetail(clientId, name);
	}

	@GET
	@Path("/getAppList/id/{id}")
	@Produces(MediaType.APPLICATION_JSON)
	public List<App> getMonitorAppsById(@PathParam("id") String id) {
		List<App> apps = new ArrayList<App>();
		App app1 = new App();
		app1.name = "gmapping";
		app1.id = "1";
		app1.version = "1.0";
		app1.cpu = 7.5;
		app1.memory = 12.0;
		app1.health = true;
		app1.state = AppState.RUNNING;

		apps.add(app1);

		App app2 = new App();
		app2.name = "BaseMove";
		app2.id = "5";
		app2.version = "1.0";
		app2.cpu = 0;
		app2.memory = 0.1;
		app2.health = true;
		app2.state = AppState.RUNNING;

		apps.add(app2);

		App app3 = new App();
		app3.name = "ORBSlam2";
		app3.id = "2";
		app3.version = "1.0";
		app3.cpu = 0;
		app3.memory = 0;
		app3.health = false;
		app3.state = AppState.STOP;

		apps.add(app3);
		return apps;

		// return new AppMonitorService().getMonitorAppsByClientId(id);
	}
}